<template>
    <div class="info-box">
        <div class="title">联系人信息</div>
        <el-form
            class="form-box"
            ref="formInfoRef"
            v-loading="loading"
            :element-loading-text="loadingText"
            :model="formInfo"
            :rules="rules"
            :inline="false"
            scroll-to-error
            :disabled="props.disabled"
            label-position="top"
            label-width="auto">
            <el-row>
                <el-col :span="24">
                    <el-form-item :label="`联系人是否为${labelText}`" prop="contact_is_lp">
                        <el-radio-group v-model="formInfo.contact_is_lp" class="ml-4">
                            <el-radio :label="1" size="large">是</el-radio>
                            <el-radio :label="2" size="large">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <template v-if="formInfo.contact_is_lp == 2">
                <el-row :gutter="60">
                    <el-col :span="8">
                        <el-form-item class="id-card-item" label="联系人身份证人像面" prop="contact_id_card_front">
                            <div class="upload-img-box">
                                <ZwUnityKitCertificateUpload
                                    v-model="formInfo.contact_id_card_front"
                                    v-model:imageList="contact_id_card_front_url"
                                    ocrType="RESIDENT_CARD_NATIONAL_HEAD"
                                    uploadLabel="上传身份证人像面"
                                    :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                    :multiple="false"
                                    :disabled="props.disabled"
                                    uploadTips=""
                                    validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M"
                                    @submit="getlpIdCardFront"
                                    @start="onStartLoading"
                                    @finished="onFinishedLoading" />
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item class="id-card-item" label="联系人身份证国徽面" prop="contact_id_card_back">
                            <div class="upload-img-box">
                                <ZwUnityKitCertificateUpload
                                    v-model="formInfo.contact_id_card_back"
                                    v-model:imageList="contact_id_card_back_url"
                                    ocrType="RESIDENT_CARD_NATIONAL_EMBLEM"
                                    uploadLabel="上传身份证国徽面"
                                    :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                    :multiple="false"
                                    :disabled="props.disabled"
                                    uploadTips=""
                                    validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M"
                                    @submit="getlpIdCardBack"
                                    @start="onStartLoading"
                                    @finished="onFinishedLoading" />
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="30">
                    <el-col :span="12">
                        <el-form-item label="" prop="name">
                            <div class="id-card-desc">
                                上传身份证后自动识别信息。支持JPG、BMP、PNG格式，图片大小不能超过1M。
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="60">
                    <el-col :span="8">
                        <el-form-item label="联系人姓名" prop="contact_name">
                            <el-input
                                v-model.trim="formInfo.contact_name"
                                placeholder="请输入联系人姓名"
                                type="text"
                                maxlength="16"
                                show-word-limit
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="身份证号码" prop="contact_id_card">
                            <el-input
                                v-model.trim="formInfo.contact_id_card"
                                placeholder="请输入身份证号码"
                                type="text"
                                maxlength="18"
                                show-word-limit
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="身份证有效期限" prop="times">
                            <ZwUnityKitDatePicker
                                v-model="formInfo.times"
                                v-model:isLongTerm="formInfo.contact_id_card_is_long"
                                type="RESIDENT" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="60">
                    <el-col :span="8">
                        <el-form-item label="联系人邮箱" prop="contact_email">
                            <el-input
                                v-model.trim="formInfo.contact_email"
                                placeholder="请输入联系人邮箱"
                                type="text"
                                maxlength="32"
                                show-word-limit
                                clearable />
                            <div class="label-desc">用于登陆账号或者接收邮件的邮箱</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人手机号" prop="contact_mobile">
                            <el-input
                                v-model.trim="formInfo.contact_mobile"
                                placeholder="请输入联系人手机号"
                                type="text"
                                maxlength="11"
                                show-word-limit
                                clearable />
                            <div class="label-desc">用于开户过程中问题反馈的联系电话</div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="60">
                    <el-col :span="8">
                        <el-form-item label="代理人委托书图片" prop="contact_agent_loa">
                            <template #label>
                                <div class="label">
                                    代理人委托书图片<span class="label-btn" @click="onDownloadTemplate">下载模板</span>
                                </div>
                            </template>
                            <div class="upload-img-box upload-img-box-bottom">
                                <ZwUnityKitCertificateUpload
                                    v-model="formInfo.contact_agent_loa"
                                    v-model:imageList="contact_agent_loa_url"
                                    :multiple="false"
                                    :disabled="props.disabled"
                                    :limitSize="4"
                                    :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                    uploadLabel="上传代理人委托书"
                                    uploadTips="支持JPG、BMP、PNG格式，图片大小不能超过4M。"
                                    validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过4M" />
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </template>
            <template v-if="formInfo.contact_is_lp == 1">
                <el-row :gutter="60">
                    <el-col :span="8">
                        <el-form-item :label="`${labelText}邮箱`" prop="lp_email">
                            <el-input
                                v-model.trim="formInfo.lp_email"
                                :placeholder="`请输入${labelText}邮箱`"
                                type="text"
                                maxlength="32"
                                show-word-limit
                                clearable />
                            <div class="label-desc">用于登陆账号或者接收邮件的邮箱</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="`${labelText}手机号`" prop="lp_mobile">
                            <el-input
                                v-model.trim="formInfo.lp_mobile"
                                :placeholder="`请输入${labelText}手机号`"
                                type="text"
                                maxlength="11"
                                show-word-limit
                                clearable />
                            <div class="label-desc">用于开户过程中问题反馈的联系电话</div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </template>
        </el-form>
    </div>
</template>
<script setup>
import { ref, reactive, computed, watch } from 'vue';

import { getRegExp, downloadImgHandler } from '@/commons/utils';

const formInfoRef = ref(null);
// 是否长期有效 1-是 2-否
const isLongTerm = ref(2);

const loading = ref(false);
const loadingText = ref('');

const emit = defineEmits(['update:modelValue']);

const props = defineProps({
    modelValue: {
        type: Object,
        default: () => {}
    },
    disabled: {
        type: Boolean,
        default: false
    },
    corpMainType: {
        type: [String, Number],
        default: 1
    }
});

const formInfo = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

const contact_id_card_front_url = ref({
    code: '',
    url: ''
});

const contact_id_card_back_url = ref({
    code: '',
    url: ''
});

const contact_agent_loa_url = ref({
    code: '',
    url: ''
});

const labelText = computed(() => {
    if (props.corpMainType == 1) {
        return '法人';
    }
    if (props.corpMainType == 2) {
        return '经营者';
    }
    return '';
});

// const formInfo = reactive({
//     contact_is_lp: 2
// });

const checkTimes = (ruls, value = [], callback) => {
    if (!value[0] || !value[1]) {
        return callback(new Error('请选择身份证有效期限'));
    }
    if (new Date(value[0]).getTime() - new Date(value[1]).getTime() >= 0) {
        return callback(new Error('结束时间需要大于开始时间'));
    }
    if (new Date(value[1]).getTime() - new Date().getTime() < 60 * 24 * 60 * 60 * 1000) {
        return callback(new Error('结束时间距当前时间需超过60天'));
    }
    callback();
};

const rules = reactive({
    contact_is_lp: [{ required: true, message: '请选择联系人是否为法人', trigger: 'change' }],
    contact_id_card_front: [{ required: true, message: '请上传身份证人像面', trigger: 'change' }],
    contact_id_card_back: [{ required: true, message: '请上传身份证国徽面', trigger: 'change' }],
    contact_name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
    contact_id_card: [
        { required: true, message: '请输入身份证号码', trigger: 'blur' },
        { pattern: getRegExp('idcard'), message: '身份证号码格式不正确', trigger: 'blur' }
    ],
    times: [{ required: true, validator: checkTimes, trigger: 'change' }],
    contact_email: [
        {
            required: true,
            message: '请输入联系人邮箱',
            trigger: 'blur'
        },
        { pattern: getRegExp('email'), message: '联系人邮箱格式不正确', trigger: 'blur' }
    ],
    contact_mobile: [
        { required: true, message: '请输入联系人手机号', trigger: 'blur' },
        { pattern: getRegExp('phone'), message: '联系人手机号格式不正确', trigger: 'blur' }
    ],
    contact_agent_loa: [{ required: true, message: '请上传代理人委托书', trigger: 'change' }],
    lp_email: [
        {
            required: true,
            message: `请输入${labelText.value}邮箱`,
            trigger: 'blur'
        },
        { pattern: getRegExp('email'), message: `${labelText.value}邮箱格式不正确`, trigger: 'blur' }
    ],
    lp_mobile: [
        { required: true, message: `请输入${labelText.value}手机号`, trigger: 'blur' },
        { pattern: getRegExp('phone'), message: `${labelText.value}手机号格式不正确`, trigger: 'blur' }
    ]
});

/**
 * 表单校验
 * @param {*} typeList 需要校验的字段，默认全校验
 */
const validate = async (typeList = []) => {
    if (typeList.length) {
        let errNum = 0;
        for (let i = 0; i < typeList?.length; i++) {
            try {
                await formInfoRef.value?.validateField(typeList[i]);
            } catch (err) {
                errNum++;
            }
        }
        return !errNum;
    } else {
        return await formInfoRef.value?.validate();
    }
};

/**
 * @description: 获取身份证人像面信息
 * @param {*} info
 * @return {*}
 */
const getlpIdCardFront = info => {
    formInfoRef.value?.clearValidate('contact_id_card_front');
    if (info) {
        const { name: contact_name, idNumber: contact_id_card } = info;
        if (contact_name && !formInfo.value.contact_name) {
            formInfo.value.contact_name = contact_name;
            formInfoRef.value?.clearValidate('contact_name');
        }
        if (contact_id_card && !formInfo.value.contact_id_card) {
            formInfo.value.contact_id_card = contact_id_card;
            formInfoRef.value?.clearValidate('contact_id_card');
        }
    }
};

/**
 * @description: 获取身份证国徽面信息
 * @param {*} info
 * @return {*}
 */
const getlpIdCardBack = info => {
    formInfoRef.value?.clearValidate('contact_id_card_back');
    if (info) {
        const { validPeriod } = info;
        if (validPeriod) {
            if (!formInfo.value.times || formInfo.value.times.filter(ite => ite).length < 2) {
                if (validPeriod.includes('长期')) {
                    formInfo.value.contact_id_card_is_long = 1;
                    const times = validPeriod.split('-')[0].replace(/\./g, '-');
                    formInfo.value.times = [times];
                } else {
                    formInfo.value.contact_id_card_is_long = 2;
                    const times = validPeriod.split('-').map(ite => ite.replace(/\./g, '-'));
                    formInfo.value.times = times;
                }
                formInfoRef.value?.clearValidate('times');
            }
        }
    }
};

watch(
    () => formInfo.value.contact_agent_loa,
    (val, oldVal) => {
        if (!oldVal && val) {
            formInfoRef.value?.clearValidate('contact_agent_loa');
        }
    }
);

const onStartLoading = () => {
    loading.value = true;
    loadingText.value = '正在识别...';
};

const onFinishedLoading = () => {
    loading.value = false;
    loadingText.value = '';
};

const onDownloadTemplate = async () => {
    if (props.disabled) return;
    downloadImgHandler(
        'https://bkt-scrm-test.oss-cn-shanghai.aliyuncs.com/keyid-payhup/third/power_attorney_temp.docx',
        '代理人委托书图片模板'
    );
};

watch(
    () => formInfo.value?.contact_id_card_front_url,
    val => {
        if (val) {
            contact_id_card_front_url.value.code = formInfo.value?.contact_id_card_front;
            contact_id_card_front_url.value.url = formInfo.value?.contact_id_card_front_url;
        }
    }
);

watch(
    () => formInfo.value?.contact_id_card_back_url,
    val => {
        if (val) {
            contact_id_card_back_url.value.code = formInfo.value?.contact_id_card_back;
            contact_id_card_back_url.value.url = formInfo.value?.contact_id_card_back_url;
        }
    }
);

watch(
    () => formInfo.value?.contact_agent_loa_url,
    val => {
        if (val) {
            contact_agent_loa_url.value.code = formInfo.value?.contact_agent_loa;
            contact_agent_loa_url.value.url = formInfo.value?.contact_agent_loa_url;
        }
    }
);

defineExpose({
    validate
});
</script>
<style lang="scss" scoped>
.el-form-item {
    margin-bottom: 24px;
}
.info-box {
    margin-bottom: 16px;
    background: #ffffff;
    .title {
        padding: 16px 24px;
        font-size: 16px;
        font-weight: 500;
        color: #333333;
        line-height: 24px;
        border-bottom: 1px solid #e9e9e9;
    }
    .form-box {
        margin: 24px 24px 0;
        .label {
            display: inline-block;
            span {
                font-size: 14px;
                color: rgba(153, 153, 153, 0.85);
                line-height: 22px;
            }
            .label-btn {
                padding-left: 16px;
                font-size: 14px;
                color: #ff6b00;
                line-height: 20px;
                cursor: pointer;
            }
        }
        .label-desc {
            padding-top: 8px;
            font-size: 12px;
            color: #999999;
            line-height: 17px;
        }
        .upload-img-box {
            width: 45%;
        }
        .upload-img-box-bottom {
            margin-bottom: 24px;
        }
        .id-card-item {
            margin-bottom: 0px;
            :deep(.el-form-item__error) {
                padding-top: 28px;
            }
        }
        .id-card-desc {
            padding-top: 8px;
            font-size: 12px;
            color: #999999;
            line-height: 17px;
        }
    }
}
</style>
